'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession, signIn, signOut } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { ROUTES } from '@/lib/constants';

interface UseAuthOptions {
  requireAuth?: boolean;
  redirectTo?: string;
  redirectIfAuthenticated?: boolean;
  redirectAuthenticatedTo?: string;
}

export function useAuth(options: UseAuthOptions = {}) {
  const {
    requireAuth = false,
    redirectTo = ROUTES.LOGIN,
    redirectIfAuthenticated = false, // 默认关闭已认证重定向
    redirectAuthenticatedTo = ROUTES.DASHBOARD,
  } = options;

  const { data: session, status, update } = useSession();
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 检查用户是否已认证
  const isAuthenticated = status === 'authenticated';
  const isLoading = status === 'loading';

  // 处理重定向
  useEffect(() => {
    if (isLoading) return;

    if (requireAuth && !isAuthenticated) {
      // 需要认证但未登录，重定向到登录页
      router.push(redirectTo);
    } else if (redirectIfAuthenticated && isAuthenticated) {
      // 已登录但需要重定向到其他页面
      router.push(redirectAuthenticatedTo);
    } else {
      setLoading(false);
    }
  }, [
    isAuthenticated,
    isLoading,
    requireAuth,
    redirectIfAuthenticated,
    redirectTo,
    redirectAuthenticatedTo,
    router,
  ]);

  // 登录方法
  const login = useCallback(
    async (email: string, password: string) => {
      setLoading(true);
      setError(null);

      try {
        const result = await signIn('credentials', {
          redirect: false,
          email,
          password,
        });

        if (result?.error) {
          setError(result.error);
          return false;
        }

        return true;
      } catch (err) {
        setError('登录失败，请稍后重试');
        return false;
      } finally {
        setLoading(false);
      }
    },
    []
  );

  // 注册方法
  const register = useCallback(
    async (name: string, email: string, password: string) => {
      setLoading(true);
      setError(null);

      try {
        // 实际开发中应调用API注册用户
        const response = await fetch('/api/auth/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ name, email, password }),
        });

        const data = await response.json();

        if (!response.ok) {
          setError(data.message || '注册失败，请稍后重试');
          return false;
        }

        // 注册成功后自动登录
        return await login(email, password);
      } catch (err) {
        setError('注册失败，请稍后重试');
        return false;
      } finally {
        setLoading(false);
      }
    },
    [login]
  );

  // 登出方法
  const logout = useCallback(async () => {
    await signOut({ redirect: false });
    router.push(ROUTES.HOME);
  }, [router]);

  // 检查用户是否有特定权限
  const hasPermission = useCallback(
    (permission: string) => {
      if (!isAuthenticated || !session?.user) return false;
      
      // 实际开发中应根据用户角色和权限系统检查
      // 这里简单示例，假设用户有permissions字段
      const userPermissions = (session.user as any).permissions || [];
      return userPermissions.includes(permission);
    },
    [isAuthenticated, session]
  );

  // 检查用户是否有特定角色
  const hasRole = useCallback(
    (role: string) => {
      if (!isAuthenticated || !session?.user) return false;
      
      // 实际开发中应根据用户角色系统检查
      // 这里简单示例，假设用户有role字段
      const userRole = (session.user as any).role;
      return userRole === role;
    },
    [isAuthenticated, session]
  );

  return {
    user: session?.user,
    isAuthenticated,
    isLoading: loading || isLoading,
    error,
    login,
    register,
    logout,
    hasPermission,
    hasRole,
    updateSession: update,
  };
} 